public class test5 {
    //力扣  25.k个一组翻转链表
    public ListNode reverseKGroup(ListNode head, int k) {
        int n = 0;
        ListNode cur = head;
        while(cur!=null){
            n++;
            cur = cur.next;
        }
        n/=k;
        ListNode newhead = new ListNode(0);
        ListNode prev = newhead;
        cur = head;

        while(n!=0){
            //创建一个临时变量记录每次翻转前的头结点
            ListNode temp = cur;
            for(int i = 0;i<k;i++){
                ListNode next = cur.next;
                cur.next = prev.next;
                prev.next = cur;
                cur = next;
            }
            //方便下一次的翻转和链接
            prev = temp;
            n--;
        }
        //连接后面不需要翻转的结点
        prev.next = cur;
        return newhead.next;
    }
}
